package com.project.collectAPI.comm;

import com.thoughtworks.xstream.XStream;
import org.apache.commons.io.IOUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class XmlReader {

    public static String XmlReaderFromInputString(String inputXMLString,String nodeName) throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
        InputStream is=ConvertStringToInputStream(inputXMLString);
        DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder domBuilder = domfac.newDocumentBuilder();
        Document doc = domBuilder.parse(is); //获取xml文档流
        /*Element root = doc.getDocumentElement();
        NodeList xlists = root.getChildNodes();
        for (int i = 0; i < xlists.getLength(); i++) {
            Node node = xlists.item(i);
            if (node instanceof Element) {
                Element ele = (Element) node;
                String name = ele.getNodeName();
                String val = ele.getTextContent();
                System.out.println("FromUserName == " + name+",val:"+val);
            }
        }*/

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        String expression = "//"+nodeName;
        Node node = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
        //System.out.println("1. " + node.getNodeName()+","+node.getTextContent());
        return node!=null?node.getTextContent():null;
    }

    public static InputStream ConvertStringToInputStream(String inputStr) throws IOException {
        InputStream targetStream = IOUtils.toInputStream(
                new String(inputStr), StandardCharsets.UTF_8.name());
        return targetStream;
    }


    /*public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException {
        Map<String,String> map=new HashMap<String, String>();
        SAXReader reader = new SAXReader();
        InputStream ins = request.getInputStream();
        org.dom4j.Document doc= reader.read(ins);
        org.dom4j.Element root = doc.getRootElement();
        List<org.dom4j.Element> list = root.elements();
        for (Element e : list){
            map.put(e.getName(),e.getText());
        }
        ins.close();
        return map;
    }*/


    //字符串转xml
    public static Document parseXmlString(String xmlStr){
        try{
            InputSource is = new InputSource(new StringReader(xmlStr));
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder=factory.newDocumentBuilder();
            Document doc = builder.parse(is);
            return doc;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    //字符串xml转map
    public static Map<String,Object> xmlToMap(String bodyXml){
        Map<String,Object> dataMap = new HashMap<String,Object>();
        Document doc = parseXmlString(bodyXml);
        if(null != doc){
            NodeList rootNode = doc.getElementsByTagName("xml");
            if(rootNode != null){
                Node root = rootNode.item(0);
                NodeList nodes = root.getChildNodes();
                for(int i = 0;i < nodes.getLength(); i++){
                    Node node = nodes.item(i);
                    dataMap.put(node.getNodeName(), node.getTextContent());
                }
            }
        }
        return dataMap;
    }



    public static String objectToXml(Object obj) {
        XStream xStream = new XStream();
        // xstream使用注解转换
        // xStream.processAnnotations(obj.getClass());
         return xStream.toXML(obj);
    }


}
